﻿using Quartz;
using Quartz.Impl;
using FRMS.DAL;
using FRMS.Model;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using FRMS.BUS;
using FRMS.Controllers;
using Microsoft.AspNetCore.WebSockets;
using static FRMS.WebSockets.DeviceWebSocketMiddleware;
using Newtonsoft.Json;
using System.Net.WebSockets;
using System.Threading;
using Microsoft.VisualStudio.Web.CodeGeneration.Contracts.Messaging;
using FRMS.WebSockets;
using System.Linq;
using System.Net.Sockets;

namespace FRMS
{
    public class WorkAbnormalAppService : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            QueryDeviceInfo();
            QueryHeart();
        }

        public void QueryDeviceInfo()
        {
            try
            {
                //if (DeviceWebSocketMiddleware._sockets != null && DeviceWebSocketMiddleware._sockets.Count > 0)
                //{
                //    List<SocketList> socketLists = DeviceWebSocketMiddleware._sockets;
                //    LogHelper.Log("WebSocket连接设备数量" + socketLists.Count.ToString());

                //    foreach (var item in socketLists)
                //    {
                //        QueryDevice(item.Socket);
                //    }
                //}

                if (DeviceWebSocketMiddleware.clientSockets != null && DeviceWebSocketMiddleware.clientSockets.Count > 0)
                {
                    List<ClientSocket> socketLists = DeviceWebSocketMiddleware.clientSockets;
                    LogHelper.Log("WebSocket连接设备数量" + socketLists.Count.ToString());
                    foreach (var item in socketLists)
                    {
                        QueryDevice(item.Socket);
                    }
                }
            }
            catch
            {

            }
        }

        public bool QueryDevice(WebSocket webSocket)
        {
            try
            {
                QueryInfo queryInfo = new QueryInfo();
                queryInfo.method = "queryInfo";
                Random random = new Random();
                queryInfo.req_id = random.Next();
                //if (webSocket.State == WebSocketState.Open)//连通状态才允许发送
                //{
                var array = new ArraySegment<byte>(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(queryInfo)));
                webSocket.SendAsync(array, WebSocketMessageType.Text, true, CancellationToken.None);
                //}
            }
            catch (Exception ex)
            {
                LogHelper.Log("WebSocket发送消息失败" + ex.ToString());
                return false;
            }

            return true;
        }

        public void QueryHeart()
        {
            try
            {
                if (DeviceWebSocketMiddleware.deviceStateInfos!=null && DeviceWebSocketMiddleware.deviceStateInfos.Count>0)
                {
                    List<DeviceStateInfo> list = DeviceWebSocketMiddleware.deviceStateInfos;
                    foreach (var item in list)
                    {
                        TimeSpan secondSpan = new TimeSpan(DateTime.Now.Ticks - item.time.Ticks);
                        if (secondSpan.TotalSeconds > 180)
                        {
                            DeviceDAL deviceDAL = new DeviceDAL();
                            bool result = deviceDAL.BatchUpdateDeviceIds(item.deviceID);
                            if (result)
                            {
                                DeviceWebSocketMiddleware.deviceStateInfos.Remove(item);
                                LogHelper.Log("设备" + item.deviceID + "超过3分钟未接收到状态，设备状态更新为离线");
                            }
                        }
                    }
                }
            }
            catch
            {

            }
        }
       
    }
}
